package com.ws.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.common.ResultUtils;
import com.constant.UserConstant;
import com.domain.dto.UserShowInfo;
import com.domain.entity.ChatMessage;
import com.ws.schedule.MessageSync;
import com.service.TeamService;
import com.ws.MessageManager;
import com.ws.SessionManager;
import com.ws.message.ChatMessageDto;
import com.ws.message.ChatMessageVo;
import com.ws.message.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import static com.common.ErrorCode.FORBIDDEN;

@Component
public class TeamMessageHandler implements MessageHandler {
    private TeamService teamService;
    private MessageManager messageManager;
    private SessionManager sessionManager;
    private MessageSync messageSync  ;

    @Override
    public Integer getMesType() {
        return MessageType.TEAM_CHAT;
    }

    @Autowired
    public TeamMessageHandler(TeamService teamService, MessageManager messageManager, SessionManager sessionManager , MessageSync messageSync) {
        this.teamService = teamService;
        this.messageSync = messageSync;
        this.messageManager = messageManager;
        this.sessionManager = sessionManager;
    }

    /**
     * 消息处理
     *
     * @param messageJson
     */
    @Override
    public void handleMessage(String messageJson) {
        ChatMessageVo chatMessageVo = JSONUtil.toBean(messageJson, ChatMessageVo.class);
        ChatMessageDto chatMessageDto = messageManager.getChatMessageDto(chatMessageVo);
        //需要查询当前群聊有哪些成员
        List<UserShowInfo> teamMembers = teamService.getTeamMember(chatMessageVo.getReceiverId());
        Optional<UserShowInfo> userShowInfoOptional = teamMembers.stream()
                .filter(user -> Objects.equals(user.getId(), chatMessageDto.getSenderId()))
                .findFirst(); // 获取第一个匹配的元素
        if (userShowInfoOptional.isPresent()) {
            UserShowInfo userShowInfo = userShowInfoOptional.get();
            chatMessageDto.setSender(userShowInfo);
        } else {
            sessionManager.sendMessage(JSONUtil.toJsonStr(ResultUtils.error(FORBIDDEN, "该用户不存在")), chatMessageDto.getSenderId());
        }
        //noneMatch都不符合返回true
        if (CollectionUtil.isEmpty(teamMembers) || teamMembers.stream().noneMatch(userShowInfo -> userShowInfo.getId().equals(chatMessageDto.getSenderId()))) {
            sessionManager.sendMessage(JSONUtil.toJsonStr(ResultUtils.error(FORBIDDEN, "不是成员或队伍不存在")), chatMessageDto.getSenderId());
            return;
        }
        ChatMessage chatMessage = BeanUtil.copyProperties(chatMessageDto, ChatMessage.class);
        //消息持久化，放入redis中，使用zset存储，value为mes,score为sendtime,privatekey是 private:uuid  groupkey是 group:teamId
        messageManager.addMessageRedisCache(chatMessage);
        chatMessageDto.setCount((int) teamMembers
                .stream()
                .filter(userShowInfo -> userShowInfo
                        .getUserStatus()
                        .equals(UserConstant.LOGIN))
                .count());
        //发送群聊消息
        sessionManager.sendBatchMessage(JSONUtil.toJsonStr(ResultUtils.success(chatMessageDto)),
                (ArrayList<Long>) teamMembers.stream()
                        .map(UserShowInfo::getId)
                        .collect(Collectors.toList()), chatMessageDto.getReceiverId());
    }

}
